package org.ihelpuoo.orm.handler.map;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.ihelpuoo.orm.IIIException;
import org.ihelpuoo.orm.ObjectRule;
import org.ihelpuoo.orm.filter.Filter;
import org.ihelpuoo.orm.handler.ObjectProcessor;

public class MapSequanceFieldUtils
{
	@SuppressWarnings("unchecked")
	static List evalObjectList(ObjectProcessor processor, ObjectRule r, Field f, Object src,
			Filter filter, Object parent, Class subType) throws Exception
	{
		String key = r.getAlias(f);
		Object v = ((Map)src).get(key);
		if (null == v)
			return null;
		if (!(v instanceof List))
		{
			throw new IIIException("Source object paire \"" + key
					+ "\" should be a List object!");
		}
		if (((List)v).size() == 0)
			return null;
		List list = new ArrayList(((List)v).size());
		Iterator it = ((List)v).iterator();
		ObjectRule subRule = processor.getManual().getRule(subType);
		while (it.hasNext())
		{
			Object sub = subType.newInstance();
			processor.fetch(subRule,it.next(),sub,null,null, null);
			list.add(sub);
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	static Object prepareSubSource(ObjectRule r, Field f, Object src) throws Exception
	{
		String key = r.getAlias(f);
		List list = new LinkedList();
		((Map)src).put(key,list);
		return list;
	}
}
